package com.woniu.controller;

import com.woniu.service.impl.RonglianSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api")
public class SmsController {

    @Autowired
    private RonglianSmsService smsService;
    @Resource
    private RedisTemplate redisTemplateInit;

    @PostMapping("/send-sms/{phone}")
    public ResponseEntity<Map<String, String>> sendSms(@PathVariable String phone) {
        // 校验手机号格式
        if (phone == null || !phone.matches("^1[3-9]\\d{9}$")) {
            Map<String, String> resp = new HashMap<>();
            resp.put("error", "手机号格式错误");
            return ResponseEntity.badRequest().body(resp);
        }

        String code = String.valueOf((int) ((Math.random() * 9000) + 1000));
        boolean success = smsService.sendVerificationCode(phone, code);
        redisTemplateInit.opsForValue().set(phone, code,5, TimeUnit.MINUTES);

        Map<String, String> resp = new HashMap<>();
        if (success) {
            resp.put("message", "验证码发送成功");
            return ResponseEntity.ok(resp);
        } else {
            resp.put("error", "短信发送失败，请稍后再试");
            return ResponseEntity.status(500).body(resp);
        }
    }
}